#include <iostream>

#include <workflow/WFFacilities.h>
#include <wfrest/HttpServer.h>
#include <nlohmann/json.hpp>


using namespace std;
using namespace wfrest;
using Json = nlohmann::json;

static WFFacilities::WaitGroup waitGroup(1);

void test0()
{
    HttpServer server;

    server.GET("/hello", [](const HttpReq * req, HttpResp * resp){
        //resp->append_output_body("method is GET, path is /hello");
        //给响应体中添加字符串
        resp->String("method is GET, path is /hello");
    });

    //重定向
    server.GET("/redirect", [](const HttpReq * req, HttpResp * resp){
        resp->set_status_code("302");
        //resp->add_header_pair("Location", "/hello");
        //设置首部字段时，可以直接使用map来操作
        resp->headers["Location"] = "/hello";
    });

    //直接获取url中的查询词
    server.GET("/query_list", [](const HttpReq * req, HttpResp * resp){
        auto & queryKV = req->query_list();
        for(auto & elem : queryKV) {
            //cout << elem.first << " -> " << elem.second << endl;
        }

        //cout << "username:" << req->query("username") << endl;
    });

    //部署静态资源
    server.GET("/login", [](const HttpReq * req, HttpResp * resp){
        resp->File("/usr/local/nginx/html/postform.html");
    });

    server.POST("/login", [](const HttpReq * req, HttpResp * resp){
        if(req->content_type() == wfrest::APPLICATION_URLENCODED) {
            auto & formKV = req->form_kv();
            cout << "username:" << formKV["username"] << endl
                 << "password:" << formKV["password"] << endl;
        }
    });


    if(server.track().start(8888) == 0) {
        server.list_routes();
        waitGroup.wait();
        server.stop();
    } else {
        printf("server cannnot start\n");
    }
}


int main()
{
    test0();
    return 0;
}

